﻿using UnityEngine;
using System.Collections;
using LitJson;

/// <summary>
/// 网络消息的总调度
/// </summary>
public class EventManager {

    private static EventManager _instance;
    public static EventManager Instance
    {
        get
        {
            if(_instance==null)
            {
                _instance = new EventManager();
            }
            return _instance;
        }
    }

    public static System.Action<string, bool> loginSuccess;//登录成功
    public static System.Action<MoveData> playerMove;//玩家已从
    public static System.Action<UserData> playerPosition;//老玩家更新
    public static System.Action<User> PlayerLogout;//玩家退出


    public void OnMessage(ByteBuffer buffer)
    {
        //处理消息
        int protocol = buffer.ReadInt();
        string msg = buffer.ReadStringOnly();
        Debug.Log("协议" + protocol + ";消息体：" + msg);

        switch (protocol)
        {
            case Protocol.Login_CMD://别人登录成功
                Debug.Log("登录成功");
                EventManager.loginSuccess(msg,false);
                break;
            case Protocol.SelfLogin_CMD://自己登录成功
                Debug.Log("登录成功");
                EventManager.loginSuccess(msg,true);
                break;
            case Protocol.PlayerLogOut://有人退出
                Debug.Log("有人退出");

                User user1 = JsonMapper.ToObject<User>(msg);
                EventManager.PlayerLogout(user1);
                break;
            case Protocol.PlayerPosition_CMD:
                Debug.Log("老用户更新");
                UserData user2 = JsonUtility.FromJson<UserData>(msg);
                EventManager.playerPosition(user2);
                break;
            case Protocol.Register_CMD:
                Debug.Log("注册成功");

                break;
            case Protocol.PlayerMove_CMD://玩家移动消息
                MoveData data = JsonUtility.FromJson<MoveData>(msg);
                EventManager.playerMove(data);
                break;
            default:
                break;
        }
    }
}
